import { isObject } from '../shared';
import { track, trigger } from './effect';
import { reactive, ReactiveFlags, readonly } from './reactive';

// 把getter函数抽离出来
function createGetter(isReadonly = false) {
	return function get(target, key) {
		
		if (key === ReactiveFlags.IS_REACTIVE) {
			return !isReadonly;
		} else if (key === ReactiveFlags.IS_READONLY) {
			return isReadonly;
		}
		const res = Reflect.get(target, key);
		// 判断res是否为对象
		if(isObject(res)) {
			return isReadonly ? readonly(res) : reactive(res)
		}
		if (!isReadonly) {
			// 依赖收集
			track(target, key);
		}
		return res;
	};
}
// 抽离setter函数
function createSetter() {
	return function set(target, key, value) {
		const res = Reflect.set(target, key, value);
		// 触发依赖
		trigger(target, key);
		return res;
	};
}

// 一开始就初始化函数
const get = createGetter();
const set = createSetter();
const readonlyGet = createGetter(true);
export const mutableHandlers = {
  // 避免重复执行
	// get: createGetter(),
	// set: createSetter()
  get,
  set
};
export const readonlyHandlers = {
	get: readonlyGet,
  // no set
  // TODO 抛出警告
  set(target, key, value) {
    console.warn(
      `key: "${key}" set 失败，因为 target 是 readonly 类型`
    );
    return true;
  }
};
